/**
 * Created by hda on 2017/6/5.
 */
define(['jquery', 'async!BMap'], function ($) {
    var model = {};

    model.init = function (m) {
        var map = new BMap.Map("map");
        var $lng = parseFloat(m.lng);
        var $lat = parseFloat(m.lat);
        var $zoom = parseFloat(m.zoom);
        if ($lng > 0 && $lat > 0) {
            if (!$zoom) {
                $zoom = 14
            }
            map.centerAndZoom(new BMap.Point($lng, $lat), $zoom);
        } else {
            map.centerAndZoom(new BMap.Point(117.214393, 34.270299), 14);//默认徐州
        }
        map.addControl(new BMap.NavigationControl());


        autoPosition();


        map.addEventListener("dragend", function () {
            var center = map.getCenter();
            console.log("地图中心点变更为：" + center.lng + ", " + center.lat + '缩放比例：' + map.getZoom());
            $("#edit_map_lng").val(center.lng);
            $("#edit_map_lat").val(center.lat);
            $("#edit_map_zoom").val(map.getZoom());
            $("#edit_map").html('已定位').removeClass('color-gray');
        });


        map.addEventListener("zoomend", function () {
            var center = map.getCenter();
            console.log("地图中心点变更为：" + center.lng + ", " + center.lat + '缩放比例：' + map.getZoom());
            $("#edit_map_lng").val(center.lng);
            $("#edit_map_lat").val(center.lat);
            $("#edit_map_zoom").val(map.getZoom());
            $("#edit_map").html('已定位').removeClass('color-gray');
        });


        function autoPosition() {
            var geolocation = new BMap.Geolocation();
            geolocation.getCurrentPosition(function (r) {
                if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                    // var mk = new BMap.Marker(r.point);
                    // map.addOverlay(mk);
                    map.panTo(r.point);
                    console.log('您的位置：' + r.point.lng + ',' + r.point.lat + '缩放比例：' + map.getZoom());


                    $("#edit_map_lng").val(r.point.lng);
                    $("#edit_map_lat").val(r.point.lat);
                    $("#edit_map_zoom").val(map.getZoom());
                    $("#edit_map").html('已定位').removeClass('color-gray');
                }
                else {
                    alert('failed' + this.getStatus());
                }
            }, {enableHighAccuracy: true})
        }


        $("#autoGPS").on('click', function () {
            autoPosition();
        })
    }

    return model
})